package com.doit.day04

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

//去mysql中找一张表，封装里面的每一行数据为一个对象以迭代器的形式返回过来
object ExerciseIterator {
  def main(args: Array[String]): Unit = {
    //1.连接mysql数据库，获取连接对象==》 迭代器的构造方法中
    //2.写一个pps，把sql写好==》还可以直接执行==》 都放在构造器里面
    //重写里面的两个方法，hasNext，next

    val iterator: MysqlIterator = new MysqlIterator
    while (iterator.hasNext){
      println(iterator.next())
    }
  }
}


class MysqlIterator extends Iterator[UserInfo]{

  //获取连接
  val conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test01", "root", "123456")
  //获取pps对象
  val pps = conn.prepareStatement("select * from user_info")
  //执行sql
  val set = pps.executeQuery()

  override def hasNext: Boolean = set.next()

  override def next(): UserInfo = {
    val id = set.getInt(1)
    val name = set.getString(2)
    val age = set.getInt(3)
    val gender = set.getString(4)
    UserInfo(id,name,age,gender)
  }
}




case class UserInfo(id:Int,name:String,age:Int,gender:String)
